<template>
  <div class="windows-desktop" @contextmenu.prevent="onDesktopContextMenu">
    <div v-if="isShutdown" class="shutdown-mask">
      正在关机...（{{ shutdownCountdown }}）
    </div>
    <div v-if="isRestarting" class="shutdown-mask">正在重启...</div>
    <!-- 桌面背景 -->
    <div class="desktop-background"></div>
    
    <!-- 桌面图标 -->
    <div class="desktop-icons">
      <DesktopIcon 
        v-for="(icon, idx) in desktopIcons" 
        :key="icon.id" 
        :icon="icon"
        :index="idx"
        :selected="selectedIconId === icon.id"
        @open="openApp"
        @rename="onRenameIcon"
        @delete="() => deleteIcon(icon.id)"
        @contextmenu.native="e => onIconContextMenu(e, icon)"
        @select="onSelectIcon"
        :style="{ left: icon.left + 'px', top: icon.top + 'px', position: 'absolute' }"
        @drag-move="(pos) => updateIconPosition(icon.id, pos.left, pos.top)"
      />
    </div>

    <!-- 右键菜单 -->
    <ContextMenu
      :visible="showMenu"
      :x="menuX"
      :y="menuY"
      :menu="menuList"
      @select="onMenuSelect"
      @close="showMenu = false"
    />

    <!-- 窗口 -->
    <Window
      v-if="activeWindow"
      :window="activeWindow"
      :position="windowPos"
      :isMaximized="isMaximized"
      @close="closeWindow"
      @minimize="minimizeWindow"
      @toggleMaximize="toggleMaximize"
    />
    
    <!-- 任务栏 -->
    <Taskbar
      :apps="taskbarApps"
      :showStartMenu="showStartMenu"
      :currentTime="currentTime"
      @toggleStartMenu="toggleStartMenu"
      @toggleApp="toggleApp"
    />
    
    <!-- 开始菜单 -->
    <StartMenu
      v-if="showStartMenu"
      :items="startMenuItems"
      @select="selectMenuItem"
      @shutdown="shutdown"
      @restart="restart"
    />
  </div>
</template>

<script setup>
import { onMounted, onBeforeUnmount, ref, computed, nextTick } from 'vue'
import DesktopIcon from './components/DesktopIcon.vue'
import ContextMenu from './components/ContextMenu.vue'
import Taskbar from './components/Taskbar.vue'
import StartMenu from './components/StartMenu.vue'
import Window from './components/Window.vue'
import Computer from './components/Computer.vue'
import Explorer from './components/Explorer.vue'
import RecycleBin from './components/RecycleBin.vue'
import Calculator from './components/Calculator.vue'
import Cmd from './components/Cmd.vue'
import Settings from './components/Settings.vue'
import Draw from './components/Draw.vue'
import Notepad from './components/Notepad.vue'
import SnippingTool from './components/SnippingTool.vue'
import Vscode from './components/Vscode.vue'
import useWindowsManager from '../../core/useWindowsManager'
import { useRouter } from 'vue-router'
import { icons as defaultIcons, taskbarApps, startMenuItems } from '../../core/desktopApps'
import folderIcon from '../../assets/home/ziyuan.png'
import shortcutIcon from '../../assets/home/huishou.png'
import bmpIcon from '../../assets/home/baidu.png'
import txtIcon from '../../assets/home/write.png'
import edgeIcon from '../../assets/home/Edge.png'
import useDesktopIcons from './useDesktopIcons'

const componentMap = {
  Computer,
  Explorer,
  RecycleBin,
  Calculator,
  Cmd,
  Settings,
  Draw,
  Notepad,
  SnippingTool,
  Vscode
}

const {
  activeWindow,
  isMaximized,
  windowPos,
  currentTime,
  openApp: originalOpenApp,
  toggleApp,
  closeWindow,
  minimizeWindow,
  toggleMaximize,
  showStartMenu,
  toggleStartMenu,
  updateTime
} = useWindowsManager()
const router = useRouter()
const iframeWhitelist = [ 'https://browser.lenovo.com' ]
const isShutdown = ref(false)
const isRestarting = ref(false)
const shutdownCountdown = ref(5)

const {
  desktopIcons,
  setIcons,
  addIcon,
  moveIcon,
  deleteIcon,
  copyIcon,
  viewIcon,
  updateIconPosition
} = useDesktopIcons()

const selectedIconId = ref(null)
function onSelectIcon(icon) {
  selectedIconId.value = icon.id
}

onMounted(() => {
  setIcons([...defaultIcons.map((icon, i) => ({...icon, id: i+1}))])
  updateTime()
  const timer = setInterval(updateTime, 1000)
  onBeforeUnmount(() => clearInterval(timer))
})
let iconIdSeed = defaultIcons.length + 1

// 右键菜单
const showMenu = ref(false)
const menuX = ref(0)
const menuY = ref(0)
const menuTargetId = ref(null)
const menuList = [
  { label: '查看', action: 'view' },
  { label: '复制', action: 'copy' },
  { label: '重命名' },
  { label: '删除' },
  { label: '刷新', action: 'refresh' },
  {
    label: '新建',
    children: [
      { label: '文件夹', type: 'folder' },
      { label: '快捷方式', type: 'shortcut' },
      { label: 'BMP 图片', type: 'bmp' },
      { label: 'DOC 文档', type: 'doc' },
      { label: 'DOCX 文档', type: 'docx' },
      { label: 'WPS PDF 文档', type: 'pdf' },
      { label: 'PPT 演示文稿', type: 'ppt' },
      { label: 'PPTX 演示文稿', type: 'pptx' },
      { label: 'RTF 文件', type: 'rtf' },
      { label: '文本文档', type: 'txt' },
      { label: 'XLS 工作表', type: 'xls' },
      { label: 'XLSX 工作表', type: 'xlsx' },
      { label: '压缩(zipped)文件夹', type: 'zip' }
    ]
  },
  { label: '显示设置', action: 'display' },
  { label: '个性化', action: 'personalize' },
  { label: '在终端中打开', action: 'terminal' },
  { label: '显示更多选项', action: 'more' }
]

function onDesktopContextMenu(e) {
  if (e.target.closest('.desktop-icon')) return
  menuX.value = e.clientX
  menuY.value = e.clientY
  menuTargetId.value = null
  showMenu.value = true
}
function onIconContextMenu(e, icon) {
  e.preventDefault()
  menuX.value = e.clientX
  menuY.value = e.clientY
  menuTargetId.value = icon.id
  showMenu.value = true
}

function onMenuSelect(item) {
  if (item.type) {
    addNewIcon(item.type)
  } else if (item.action === 'refresh') {
    window.location.reload()
  } else if (item.action === 'display') {
    alert('显示设置功能待实现')
  } else if (item.action === 'personalize') {
    alert('个性化功能待实现')
  } else if (item.action === 'terminal') {
    alert('终端功能仅支持Electron环境')
  } else if (item.action === 'more') {
    alert('更多选项功能待实现')
  } else if (item.action === 'delete' || item.label === '删除') {
    if (menuTargetId.value) deleteIcon(menuTargetId.value)
  } else if (item.action === 'copy' || item.label === '复制') {
    if (menuTargetId.value) copyIcon(menuTargetId.value)
  } else if (item.action === 'view' || item.label === '查看') {
    if (menuTargetId.value) viewIcon(menuTargetId.value)
  }
}

function addNewIcon(type) {
  const typeMap = {
    folder: { name: '新建 文件夹', image: folderIcon },
    shortcut: { name: '新建 快捷方式', image: shortcutIcon },
    bmp: { name: '新建 BMP 图片.bmp', image: bmpIcon },
    doc: { name: '新建 DOC 文档.doc', image: edgeIcon },
    docx: { name: '新建 DOCX 文档.docx', image: edgeIcon },
    pdf: { name: '新建 PDF 文档.pdf', image: edgeIcon },
    ppt: { name: '新建 PPT 演示文稿.ppt', image: edgeIcon },
    pptx: { name: '新建 PPTX 演示文稿.pptx', image: edgeIcon },
    rtf: { name: '新建 RTF 文件.rtf', image: edgeIcon },
    txt: { name: '新建 文本文档.txt', image: txtIcon },
    xls: { name: '新建 XLS 工作表.xls', image: edgeIcon },
    xlsx: { name: '新建 XLSX 工作表.xlsx', image: edgeIcon },
    zip: { name: '新建 压缩文件夹.zip', image: edgeIcon }
  }
  let baseName = typeMap[type].name
  let name = baseName
  let idx = 1
  while (desktopIcons.value.some(i => i.name === name)) {
    name = baseName.replace(/(\.[^.]+)?$/, `(${idx++})$1`)
  }
  addIcon({
    id: ++iconIdSeed,
    name,
    image: typeMap[type].image,
    type
  })
}

function onRenameIcon({icon, newName}) {
  const target = desktopIcons.value.find(i => i.id === icon.id)
  if (target) target.name = newName
}

// 拖拽排序
let dragIndex = null
function onDragStart(idx) {
  dragIndex = idx
}
function onDrop(idx) {
  if (dragIndex !== null && dragIndex !== idx) {
    moveIcon(dragIndex, idx)
  }
  dragIndex = null
}
function onDragOver(e) {
  e.preventDefault()
}

function openApp(app) {
  if (app.url && (!app.component || app.component === null)) {
    if (iframeWhitelist.some(url => app.url.startsWith(url))) {
      originalOpenApp({ ...app, url: app.url })
    } else {
      window.open(app.url, '_blank')
    }
    return
  }
  if (app.component && typeof app.component === 'string' && componentMap[app.component]) {
    originalOpenApp({ ...app, componentInstance: componentMap[app.component] })
  } else {
    originalOpenApp({ ...app })
  }
}

function selectMenuItem(item) {
  showStartMenu.value = false
  openApp(item)
}

function shutdown() {
  isShutdown.value = true
  shutdownCountdown.value = 5
  const timer = setInterval(() => {
    shutdownCountdown.value--
    if (shutdownCountdown.value <= 0) {
      clearInterval(timer)
      router.push('/')
    }
  }, 1000)
}

function restart() {
  isRestarting.value = true
  setTimeout(() => {
    isRestarting.value = false
    window.location.reload()
  }, 3000)
}

onMounted(() => {
  updateTime()
  const timer = setInterval(updateTime, 1000)
  onBeforeUnmount(() => clearInterval(timer))
})
</script>

<style lang="scss" scoped>
.windows-desktop {
  position: relative;
  width: 100vw;
  height: 100vh;
  font-family: 'Segoe UI', system-ui, -apple-system, sans-serif;
  user-select: none;
}

.desktop-background {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-image: url('../../assets/home/bg.jpg');
  background-size: cover;
  background-position: center;
  z-index: 1;
}

.desktop-icons {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: calc(100% - 40px);
  padding: 20px;
  display: flex;
  flex-direction: column;
  flex-wrap: wrap;
  align-content: flex-start;
  gap: 30px;
  z-index: 2;
}

.shutdown-mask {
  position: fixed;
  z-index: 9999;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  background: #000;
  color: #fff;
  font-size: 2.5rem;
  display: flex;
  align-items: center;
  justify-content: center;
  letter-spacing: 2px;
}

.poweron-btn {
  font-size: 1.5rem;
  padding: 12px 48px;
  border-radius: 8px;
  border: none;
  background: #0078d7;
  color: #fff;
  cursor: pointer;
  transition: background 0.2s;
}
.poweron-btn:hover {
  background: #005fa3;
}
</style>